package com.authine.cloudpivot.ext.applicationservice;

import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.cola.exception.Assert;
import com.alibaba.cola.exception.BizException;
import com.alibaba.fastjson.JSON;
import com.authine.cloudpivot.ext.conf.ApplicationConf;
import com.authine.cloudpivot.ext.domain.bo.MarketGoodsSettingBo;
import com.authine.cloudpivot.ext.domain.dto.MarketGoodsSettingDto;
import com.authine.cloudpivot.ext.domain.dto.RotationImagesDto;
import com.authine.cloudpivot.ext.domain.vo.MarketGoodsSettingVo;
import com.authine.cloudpivot.ext.domain.vo.MarketGoodsVo;
import com.authine.cloudpivot.ext.domain.vo.MarketSettingVo;
import com.authine.cloudpivot.ext.domain.vo.RotationImagesVo;
import com.authine.cloudpivot.ext.util.BoServiceUtils;
import com.authine.cloudpivot.ext.util.BoUtils;
import com.authine.cloudpivot.ext.util.PmUtil;
import com.authine.hermes.app.launcher.cmd.Attachment;
import com.authine.hermes.app.launcher.service.ApplicationService;
import com.authine.mvp.app.launcher.domain.AttachmentFormat;
import com.authine.mvp.app.launcher.dto.bo.query.ListBOQuery;
import com.authine.mvp.app.launcher.dto.bo.query.expression.Operator;
import com.authine.mvp.app.launcher.dto.bo.response.BO;
import com.authine.mvp.app.launcher.dto.bo.response.BOList;
import com.google.common.collect.Maps;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.ws.rs.POST;
import javax.ws.rs.Path;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static com.authine.hermes.app.launcher.service.ApplicationServiceFoundation.CUSTOM_SERVICE;

/**
 * @program: gm-market
 * @description: 市场配置
 * @author: wlw
 * @create: 2021-08-09 15:50
 **/
@Path("MarketGoodsSettingService")
@Slf4j
public class MarketGoodsSettingService extends ApplicationService {
    @POST
    @Path("getMarketGoodsSetting")
    @Operation(summary = "市场配置-获取市场配置", tags = CUSTOM_SERVICE)
    public SingleResponse<MarketSettingVo> getMarketGoodsSetting() {
        MarketSettingVo.MarketSettingVoBuilder builder = MarketSettingVo.builder();
        ListBOQuery marketSettingQuery = new ListBOQuery();
        marketSettingQuery.setSchemaCode(ApplicationConf.MARKETSETTING);
        List<Map<String, Object>> moduleData = boService.list(marketSettingQuery).getData().getData();
        if(!CollectionUtils.isEmpty(moduleData)){
            builder.marketGoodsSettingVos(moduleData.stream().map(v->{
                MarketGoodsSettingVo vo = MarketGoodsSettingVo.builder()
                        .id((String) v.get("id"))
                        .imageUrl(BoUtils.copy2List(v.get("module_image"),AttachmentFormat.class))
                        .catalogId((String) v.get("module_setting"))
                        .description((String) v.get("description"))
                        .name((String) v.get("catalog_name"))
                        .build();
                if (((String) v.get("goods_ids")).split(",").length>0){
                    vo.setGoodsFullModels(BoServiceUtils.findListBySimple(ApplicationConf.GOODES, "id", Arrays.asList(((String) v.get("goods_ids"))
                            .split(",")), Operator.IN)
                            .getData()
                            .getData()
                            .stream()
                            .filter(t->1 == (Integer)t.get("saled") &&
                                    0 == (Integer)t.get("deleted") &&
                                    1 == (Integer)t.get("enabled") &&
                                    BoUtils.dateFormat((String)t.get("expiry")).getTime()>System.currentTimeMillis())
                            .peek(m->{
                                MarketGoodsVo goodsVo = BoUtils.Map2Bo(m, MarketGoodsVo.class);
                                Map<String, BigDecimal> map = PmUtil.calculateSkuPrice(goodsVo);
                                m.put("price",map.get("showPrice"));
                                m.put("pretax_price",map.get("showPretaxPrice"));
                            }).collect(Collectors.toList()));
                }
                return vo;
            }).collect(Collectors.toList()));
        }
        ListBOQuery rotationQuery = new ListBOQuery();
        rotationQuery.setSchemaCode(ApplicationConf.SETTING_ROTATION_IMAGES);
        List<Map<String, Object>> rotationQueryData = boService.list(rotationQuery).getData().getData();
        if(!CollectionUtils.isEmpty(rotationQueryData)){
            List<RotationImagesVo> rotationImagesVos = BoUtils.copy2List(rotationQueryData, RotationImagesVo.class);
            builder.rotationImagesVo(CollectionUtils.firstElement(rotationImagesVos));
        }
        return SingleResponse.of(builder.build());
    }

    @POST
    @Path("saveOrUpdateModules")
    @Operation(summary = "市场配置-创建或更新模块配置", tags = CUSTOM_SERVICE)
    public SingleResponse<BO> saveOrUpdateModules(@Parameter MarketGoodsSettingDto marketGoodsSettingDto) {
        Assert.isTrue(Objects.nonNull(marketGoodsSettingDto), "参数不能为空");
        if (StringUtils.isEmpty(marketGoodsSettingDto.getId())) {
            //校验商品
            if(!StringUtils.isEmpty(marketGoodsSettingDto.getGoods_ids())){
                String[] ids = marketGoodsSettingDto.getGoods_ids().split(",");
                List<String> list = Arrays.asList(ids).stream().filter(m->!StringUtils.isEmpty(m)).collect(Collectors.toList());
                if(!CollectionUtils.isEmpty(list)) {
                    BOList data = BoServiceUtils.findListBySimple(ApplicationConf.GOODES, "id", list, Operator.IN).getData();
                    if (Objects.nonNull(data) && !CollectionUtils.isEmpty(data.getData())) {
                        if (data.getData().size() < list.size()) {
                            List<String> idList = data.getData().stream().map(t -> (String) t.get("id")).collect(Collectors.toList());
                            list.removeAll(idList);
                            throw new BizException("商品序列号：" + (String.join(",", list)) + "不可用,请检查");
                        }
                        for (Map<String, Object> bo : data.getData()) {
                            Assert.isTrue(Objects.nonNull(bo) && 0 == (Integer) bo.get("deleted"), "此商品不存在");
                            Assert.isTrue(1 == (Integer) bo.get("saled"), "商品已下架");
                            Assert.isTrue(1 == (Integer) bo.get("enabled"), "商品已不可采购");
                            Assert.isTrue(3 == Integer.parseInt((String) bo.get("review_status")), "商品未通过审核，不可配置");
                            Assert.isTrue(BoUtils.dateFormat((String) bo.get("expiry")).getTime() > System.currentTimeMillis(), "商品已过期");
                        }
                    }
                }
            }
            return BoServiceUtils.createBo(ApplicationConf.MARKETSETTING, BoUtils.bo2Map(marketGoodsSettingDto));
        }
            return BoServiceUtils.updateBo(ApplicationConf.MARKETSETTING, BoUtils.bo2Map(marketGoodsSettingDto));
    }

    @POST
    @Path("saveOrUpdateRotationImageModules")
    @Operation(summary = "市场配置-创建或更新轮播图配置", tags = CUSTOM_SERVICE)
    public SingleResponse saveOrUpdateRotationImageModules(@Parameter RotationImagesDto rotationImagesDto) {
        Assert.isTrue(Objects.nonNull(rotationImagesDto), "参数不能为空");
        if (StringUtils.isEmpty(rotationImagesDto.getId())) {
            return BoServiceUtils.createBo( ApplicationConf.MARKETSETTING, JSON.parseObject(JSON.toJSONString(rotationImagesDto)));
        }
           return BoServiceUtils.createBo( ApplicationConf.MARKETSETTING, JSON.parseObject(JSON.toJSONString(rotationImagesDto)));
    }

}
